//
//  TestingViewController.m
//  Estate
//
//  Created by wangdongdong on 2016/10/31.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define DIC_DATE @"date"

#import "TestingViewController.h"
#import "SampleProcessModel.h"
#import "NewInspectionTextCell.h"

#import "SubLBXScanViewController.h"
#import "SampleCodeModel.h"
#import "WitnessSamplesDetailVC.h"
#import "SampleProcessModel.h"

@interface TestingViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>{
    MJRefreshNormalHeader *header;
}

//表格
@property(strong, nonatomic)UITableView *tableView;
//数据
@property(strong ,nonatomic)NSMutableArray *dataArray;
// 扫描的二维码
@property (copy, nonatomic)NSString *erCode;

// 蒙版View
@property (strong, nonatomic) UIView *mainView;

// 记录输入次数
@property (assign, nonatomic) int number;

// 当前项目所有流程的二维码数据
@property (strong, nonatomic) NSArray *codeArr;

// 当前流程数据
@property (strong, nonatomic) NSDictionary *processDic;

// 记录扫过的二维码
@property (strong, nonatomic) NSMutableArray *qrCodeArr;

// 记录扫过的防伪码
@property (strong, nonatomic) NSMutableArray *securityCodeArr;

@end


@implementation TestingViewController

- (LSAlartView *)alertView{
    if(!_alertView){
        _alertView=[[LSAlartView alloc]initWithFrame:self.view.bounds];
    }
    return _alertView;
}

- (NSMutableArray *)securityCodeArr {
    if (!_securityCodeArr) {
        _securityCodeArr = [NSMutableArray array];
    }
    return _securityCodeArr;
}


- (NSMutableArray *)qrCodeArr {
    if (!_qrCodeArr) {
        _qrCodeArr = [NSMutableArray array];
    }
    return _qrCodeArr;
}

- (NSDictionary *)processDic {
    if (!_processDic) {
        _processDic = [NSDictionary dictionary];
    }
    return _processDic;
}

- (NSArray *)codeArr {
    if (!_codeArr) {
        _codeArr = [NSArray array];
    }
    return _codeArr;
}

-(NSMutableArray *)dataArray{
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-49)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
        _tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
    }
    return _tableView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.number = 5;
    [self createView1];
    [self initDataSource];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadGJList) name:@"reloadData" object:nil];
    
    /*
     *  添加下拉刷新
     */
    header = [MJRefreshNormalHeader headerWithRefreshingTarget:self
                                                                     refreshingAction:@selector(headRefresh)];
    [header beginRefreshing];
    // 设置字体
    header.stateLabel.font = [UIFont systemFontOfSize:13];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:12];
    self.tableView.mj_header=header;
    //同步数据
    self.dataSync =[[DataSynchronization alloc]init];
    //网络监测
    [LSHttpTool checkNetWorkForView:self.view];
}

-(void)headRefresh{
    [self reloadGJList];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2. * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}

-(void)reloadGJList {
    [self.dataArray removeAllObjects];
    [self initDataSource];
}

//创建添加btn
- (void)createView1 {
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    UIButton *addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 460, 100, 100)];
    addBtn.tag = 3;
    [addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(clickAddBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
}

// 查询属于当前项目的所有流程的所有二维码
- (void)getCode {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAMPLE_PROCESS WHERE PRO_ID = '%@'", PROID];
    FMResultSet *result=[db executeQuery:sql];
    
    NSMutableArray *arr = [NSMutableArray array];
    while ([result next]) {
        NSString *ID = [result stringForColumn:@"ID"];
        NSString *codeStr = [result stringForColumn:@"SAMPLE_QR_CODE"];
        NSString *state = [result stringForColumn:@"SAMPLE_PROCESS_STATE"];
        
        NSDictionary *dic = @{@"ID":ID, @"CODE":codeStr, @"STATE": state};
        [arr addObject:dic];
    }
    self.codeArr = arr;
    [db close];
}

/*
 * 初始化数据 查询列表数据
 */
- (void)initDataSource
{
    // 清空数据源
    [self.dataArray removeAllObjects];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result=[db executeQuery:SQL_SAMPLE_PROCESS_SELECT_JCF(PROID)];
    
    //    NSLog(@"sql:%@",SQL_SAMPLE_PROCESS_SELECT_JCF(PROID));
    
    NSMutableDictionary *dic;
    while ([result next]) {
        // 查询到 年
        NSString* year= [result stringForColumn:@"year"];
        // 查询到月
        NSString *month =[result stringForColumn:@"month"] ;
        /*
         * 根据日期查询展开的数据
         */
        NSString *sqlStr = [NSString stringWithFormat:@"SELECT *, substr(CREATE_TIME, 1, 4) as YEAR, substr(CREATE_TIME,6,2) as MONTH, substr(CREATE_TIME, 9, 2) as DAY FROM SAMPLE_PROCESS WHERE YEAR = '%@' AND MONTH = '%@' AND PRO_ID = '%@' AND SAMPLE_PROCESS_STATE = '2' AND ID IN (SELECT PROCESS_ID FROM SAMPLE_PROCESS_RECORD) ORDER BY CREATE_TIME desc", year, month, PROID];
        FMResultSet *results = [db executeQuery:sqlStr];
        
        //查询到记录
        NSMutableArray *DetailArr = [NSMutableArray array];
        while ([results next]) {
            SampleProcessModel *spModel = [[SampleProcessModel alloc] init];
            
            spModel.ID = [results stringForColumn:@"ID"];
            spModel.PRO_ID = [results stringForColumn:@"PRO_ID"];
            spModel.SAMPLE_NUMBER = [results stringForColumn:@"SAMPLE_NUMBER"];
            spModel.SAMPLE_GET_TIME = [results stringForColumn:@"SAMPLE_GET_TIME"];
            spModel.SAMPLE_GET_ADDRESS = [results stringForColumn:@"SAMPLE_GET_ADDRESS"];
            spModel.SAMPLE_GET_ADDRESS_INFO = [results stringForColumn:@"SAMPLE_GET_ADDRESS_INFO"];
            spModel.SAMPLE_WINESS_USER = [results stringForColumn:@"SAMPLE_WINESS_USER"];
            spModel.SAMPLE_QR_CODE = [results stringForColumn:@"SAMPLE_QR_CODE"];
            spModel.SAMPLE_PROCESS_STATE = [results stringForColumn:@"SAMPLE_PROCESS_STATE"];
            spModel.EXTEND_INFO = [results stringForColumn:@"EXTEND_INFO"];
            spModel.CREATE_USER_NAME = [results stringForColumn:@"CREATE_USER_NAME"];
            spModel.CREATE_TIME = [results stringForColumn:@"CREATE_TIME"];
            spModel.CREATE_IP = [results stringForColumn:@"CREATE_IP"];
            spModel.MODIFY_USER_NAME = [results stringForColumn:@"MODIFY_USER_NAME"];
            spModel.MODIFY_TIME = [results stringForColumn:@"MODIFY_TIME"];
            spModel.MODIFY_IP = [results stringForColumn:@"MODIFY_IP"];
            spModel.day = [results stringForColumn:@"DAY"];
            [DetailArr addObject:spModel];
        }
        //查询到数量
        NSString *counts=[result stringForColumn:@"COUNT(*)"];
        //拼接成标题
        NSString *tiemAndCount = [NSString stringWithFormat:@"%@年%@月 (%@条)", year, month, counts];
        //创建一个字典 包含数组，分组名，是否展开的标示
        dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr, DIC_ARARRY, tiemAndCount, DIC_TITILESTRING, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
        //将字典加入数组
        [self.dataArray addObject:dic];
    }
    
    [self.tableView reloadData];
    
    [db close];
}

/*
 * 添加事件 点击按钮 tag:2 扫描防伪码 tag:3 列表页扫描
 */

- (void)clickAddBtn:(UIButton *)Btn {
    
    if (Btn.tag == 3) {
        self.number = 5;
        self.qrCodeArr = nil;
        self.securityCodeArr = nil;
        self.erCode = nil;
    }
    
    [self.mainView removeFromSuperview];
    
    if (![self cameraPemission])
    {
        [self showError:@"没有摄像机权限"];
        return;
    }
    
    // 扫码页面风格
    LBXScanViewStyle *style = [self changeColor];
    
    SubLBXScanViewController *vc = [SubLBXScanViewController new];
    vc.style = style;
    // 开启只识别矩形框内图像功能
    vc.isOpenInterestRect = YES;
    
    if (Btn.tag == 3) {
        [LSHttpTool checkNetWork:^(NSString *status) {
            if([status isEqualToString:@"0"]){
                [LSUtility showToastWithMessage:@"请连接网络！" inView:self.view Andtime:1.5];
            }else
            {
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
    }else{
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    // 扫码回调
    vc.QRCodeBlock = ^(NSString *QRCode) {
        
        if (Btn.tag == 1 || Btn.tag == 3) {
            
            BOOL boo=[LSUtility isPureInt:QRCode];
            
            if(boo){
                // 二维码 本地
                // [self scanningErWeiMa:QRCode];
                //二维码 走网络请求
                [self scanningErWeiMaPost:QRCode];
            }else{
                [LSUtility showToastWithMessage:@"您扫描的二维码不满足为14位纯数字的要求！" inView:self.view Andtime:1.];
            }
        } else if (Btn.tag == 2) {
            /*
             *  308 防伪码
             */

            [self scanningFangWeiMa:QRCode];
        }
    };
}

#pragma mark - 第二次以后扫描二维码 均有5次机会

- (void)secondSaoMa{
    [self.mainView removeFromSuperview];
    
    if (![self cameraPemission])
    {
        [self showError:@"没有摄像机权限"];
        return;
    }
    
    // 扫码页面风格
    LBXScanViewStyle *style = [self changeColor];
    
    SubLBXScanViewController *vc = [SubLBXScanViewController new];
    vc.style = style;
    // 开启只识别矩形框内图像功能
    vc.isOpenInterestRect = YES;
    
    [LSHttpTool checkNetWork:^(NSString *status) {
        if([status isEqualToString:@"0"]){
            [LSUtility showToastWithMessage:@"请连接网络！" inView:self.view Andtime:1.5];
        }else
        {
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];

    // 扫码回调
    vc.QRCodeBlock = ^(NSString *QRCode) {
        
        BOOL boo=[LSUtility isPureInt:QRCode];
        
        if(boo){
            // 二维码 本地
            // [self scanningErWeiMa:QRCode];
            //二维码 走网络请求
            [self scanningErWeiMaPost:QRCode];
        }else{
            NSLog(@"二维码错误");
            self.number--;
            if (self.number > 0) {
                NSString *str = [NSString stringWithFormat:@"请重新进行二维码验证，剩余%d次机会", self.number];
                [self popView:@"fangweicuowu" withTitle:@"二维不存在" withDetail:str andBth:nil andResult:@"取样存疑" andType:YES];
                
            // 二维码五次机会用完
            } else {
                [UIView animateWithDuration:1.0 animations:^{
                    self.mainView.alpha = 0.0;
                    
                } completion:^(BOOL finished) {
                    [self.mainView removeFromSuperview];
                }];
                
                [LSUtility showToastWithMessage:@"5次机会已用完" inView:self.navigationController.view Andtime:1.];
                // 修改见证取样流程
                [self modifySampleProcess:@"3"];
                // 新增见证取样流程记录
                [self addFlowRecordData:@"3"];
            }
        }
        
    };

    
}


#pragma mark - 调用网络接口

- (void)scanningErWeiMaPost:(NSString *)QRCode{
    
    NSMutableDictionary *parameterDic=[NSMutableDictionary dictionary];
    [parameterDic setObject:QRCode forKey:@"sampleQrCode"];
    
    [LSHttpTool Post:URL_SAMPLE_POST parameters:parameterDic success:^(id responseObject) {
        NSLog(@"二维码返回：%@",parameterDic);
        
        NSString *code=responseObject[@"code"];
        
        if([code isEqualToString:@"0"]){
            NSString *msg=responseObject[@"msg"];
            [LSUtility showToastWithMessage:msg inView:self.view Andtime:2.];

            return ;
            
        }else if( [code isEqualToString:@"1"]){
//            NSLog(@"返回：%@ ,msg:%@",responseObject,responseObject[@"msg"]);
            //存储服务器返回
            //判断此条数据 在此期间有无其他端口进行操作
            self.responseObjectDic=[responseObject[@"data"]lastObject] ;
            [self checkErweiMa:QRCode];
        }else{
            [LSUtility showToastWithMessage:@"数据异常" inView:self.view Andtime:2.];
        }
        
    } failure:^(NSError *error) {
        [LSUtility showToastWithMessage:@"请求发生错误,请稍后重试" inView:self.view Andtime:2.];
    }];

}

//验证是否存在
- (void)checkErweiMa :(NSString *)QRCode{
    //本次存数扫过的二维码
    if ([self.qrCodeArr containsObject:QRCode]) {
        
        NSLog(@"二维码重复");
        self.number--;
        if (self.number > 0) {
            NSString *str = [NSString stringWithFormat:@"请重新进行二维码验证，剩余%d次机会", self.number];
            [self popView:@"fangweicuowu" withTitle:@"此二维码被扫过" withDetail:str andBth:nil andResult:@"取样存疑" andType:YES];
            
            // 二维码五次机会用完
        } else {
            [UIView animateWithDuration:1.0 animations:^{
                self.mainView.alpha = 0.0;
                
            } completion:^(BOOL finished) {
                [self.mainView removeFromSuperview];
            }];
            
            [LSUtility showToastWithMessage:@"5次机会已用完" inView:self.navigationController.view Andtime:1.];
            // 修改见证取样流程
            [self modifySampleProcess:@"3"];
            // 新增见证取样流程记录
            [self addFlowRecordData:@"3"];
        }
        
        return ;
        
    } else {
        // 记录刚刚扫到的二维码
        self.erCode = QRCode;
    }
    
    // 验证扫到的二维码是否在流程见证取样流程表中存在 并把SAMPLE_PROCESS详情给他
    self.processDic = [self codeExist:QRCode];
    
    // 流程为待检验
    if ([self.processDic [@"STATE"] isEqualToString:@"1"]) {
        
        /* 
         *  创建二维码存在视图  此处进入扫防伪码
         */
        
        [self popCodeExistView:@""];
        
    }
    
    
     // 流程为防伪通过
    else if ([self.processDic [@"STATE"] isEqualToString:@"2"]) {
        [LSUtility showToastWithMessage:@"此样品已通过检测" inView:self.navigationController.view Andtime:1.5];
 
    }
    // 流程为防伪不通过
    else if ([self.processDic [@"STATE"] isEqualToString:@"3"]) {
        [LSUtility showToastWithMessage:@"样品拒检" inView:self.navigationController.view Andtime:1.5];
    }
    // 二维码不存在
    else {
        [self popView:@"bucunzai" withTitle:@"对不起, 您扫描的样品信息" withDetail:@"系统中不存在!" andBth:@"确定" andResult:@"取样存疑" andType:nil];
    }
    
}

#pragma  mark - 扫的是防伪码
- (void)scanningFangWeiMa:(NSString *)QRCode{
    //得到防伪码
    NSArray *fangWeiDicArr=self.responseObjectDic[@"qrCodeSecurityCodeMap"];
    //判断防伪是否正确
    BOOL fangWeiSecurity=NO;
    
    for (NSDictionary *dic in fangWeiDicArr) {
        //二维码
        NSString *sampleQrCode=dic[@"sampleQrCode"] ;
        //防伪码
        NSString *sampleSecurityCode=dic[@"sampleSecurityCode"] ;
        if([self.erCode isEqualToString:sampleQrCode] && [QRCode isEqualToString:sampleSecurityCode]){
            fangWeiSecurity=YES;
            break;
        }else{
            fangWeiSecurity=NO;
        }
    }
    
    if (self.number > 0) {
        if(fangWeiSecurity){
            NSLog(@"防伪正确");
            // 记录扫过的通过的二维码
            [self.qrCodeArr addObject:self.erCode];
            // 记录扫过的防伪码
            [self.securityCodeArr addObject:QRCode];
            //每个二维码都扫描完成
            if (self.qrCodeArr.count == fangWeiDicArr.count) {
                self.number = 5;
                // 修改见证取样流程
                [self modifySampleProcess:@"2"];
                // 新增见证取样流程记录
                [self addFlowRecordData:@"2"];
                // 初始化列表
                [self reloadGJList];
                [self popView:@"fangweichenggong" withTitle:@"防伪验证通过!" withDetail:@"请查阅详细见证取样记录" andBth:@"查看" andResult:@"取样成功" andType:nil];
                
            }
            //再次扫描下一个二维码
            else{
                [self popSecurityCodeTureView:fangWeiDicArr];
            }
        }
        // 防伪码不正确
        else{
            NSLog(@"防伪错误");
            self.number--;
            if (self.number > 0) {
                NSString *str = [NSString stringWithFormat:@"请重新进行防伪验证，剩余%d次机会", self.number];
                [self popView:@"fangweicuowu" withTitle:@"防伪验证不通过!" withDetail:str andBth:nil andResult:@"取样成功" andType:YES];
                
                // 五次机会用完
            } else {
                [UIView animateWithDuration:1.0 animations:^{
                    self.mainView.alpha = 0.0;
                    
                } completion:^(BOOL finished) {
                    [self.mainView removeFromSuperview];
                }];
                
                [LSUtility showToastWithMessage:@"5次机会已用完" inView:self.navigationController.view Andtime:1.];
                // 修改见证取样流程
                [self modifySampleProcess:@"3"];
                // 新增见证取样流程记录
                [self addFlowRecordData:@"3"];
            }
        }
    }else{
        [LSUtility showToastWithMessage:@"5次机会已用完" inView:self.navigationController.view Andtime:1.];
    }
    
    
}



#pragma  mark -扫二维码的操作 本地操作
- (void)scanningErWeiMa:(NSString *)QRCode{
    
    // 验证扫到的二维码是否在流程见证取样流程表中存在 并把SAMPLE_PROCESS详情给他
    self.processDic = [self codeExist:QRCode];
    
    //本次存数扫过的二维码
    if ([self.qrCodeArr containsObject:QRCode]) {
        
        [LSUtility showToastWithMessage:@"此二维码已经被扫过" inView:self.view Andtime:1.];
        
        return ;
        
    } else {
        // 记录刚刚扫到的二维码
        self.erCode = QRCode;
    }
    
    // 流程为待检验
    if ([self.processDic [@"STATE"] isEqualToString:@"1"]) {
        // 查找序列号
        NSString *number = [self serialNumberByCode:QRCode];
        if (number) {
            [self popCodeExistView:number];
        }
        // 流程为防伪通过
    } else if ([self.processDic [@"STATE"] isEqualToString:@"2"]) {
        [LSUtility showToastWithMessage:@"此样品已通过检测" inView:self.navigationController.view Andtime:1.5];
        // 流程为防伪不通过
    } else if ([self.processDic [@"STATE"] isEqualToString:@"3"]) {
        [LSUtility showToastWithMessage:@"样品拒检" inView:self.navigationController.view Andtime:1.5];
        // 二维码不存在
    } else {
        [self popView:@"bucunzai" withTitle:@"对不起, 您扫描的样品信息" withDetail:@"系统中不存在!" andBth:@"确定" andResult:@"取样存疑" andType:nil];
    }
}


#pragma mark -自定义4个角及矩形框颜色
- (LBXScanViewStyle *)changeColor
{
    // 设置扫码区域参数
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    style.centerUpOffset = 44;
    // 扫码框周围4个角的类型设置为在框的上面
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_On;
    // 扫码框周围4个角绘制线宽度
    style.photoframeLineW = 6;
    //  扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    // 扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    // 显示矩形框
    style.isNeedShowRetangle = YES;
    // 动画类型：网格形式，模仿支付宝
    style.anmiationStyle = LBXScanViewAnimationStyle_NetGrid;
    style.animationImage = [UIImage imageNamed:@"hengxian"];;
    // 码框周围4个角的颜色
    style.colorAngle = [UIColor colorWithRed:65./255. green:174./255. blue:57./255. alpha:1.0];
    // 矩形框颜色
    style.colorRetangleLine = [UIColor colorWithRed:247/255. green:202./255. blue:15./255. alpha:1.0];
    // 非矩形框区域颜色
    style.red_notRecoginitonArea = 247./255.;
    style.green_notRecoginitonArea = 202./255;
    style.blue_notRecoginitonArea = 15./255;
    style.alpa_notRecoginitonArea = 0.2;
    
    return style;
}

// 验证扫到的二维码是否在流程见证取样流程表中存在 并把SAMPLE_PROCESS详情给他
- (NSDictionary *)codeExist:(NSString *)code {
    NSDictionary *dataDic = [NSDictionary dictionary];
    [self getCode];
    for (NSDictionary *dic in self.codeArr) {
        NSString *str = dic[@"CODE"];
        // 将string字符串转换为array数组
        NSArray *array = [str componentsSeparatedByString:@","]; // 分隔符逗号
        
        // 扫到的二维码是否属于此数组
        if ([array containsObject:code]) {
            dataDic = dic;
        }
    }
    return dataDic;
}

- (void)showError:(NSString*)str
{
    [LBXAlertAction showAlertWithTitle:@"提示" msg:str chooseBlock:nil buttonsStatement:@"知道了",nil];
}

- (BOOL)cameraPemission
{
    BOOL isHavePemission = NO;
    if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)])
    {
        AVAuthorizationStatus permission =
        [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        switch (permission) {
            case AVAuthorizationStatusAuthorized:
                isHavePemission = YES;
                break;
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
                break;
            case AVAuthorizationStatusNotDetermined:
                isHavePemission = YES;
                break;
        }
    }
    return isHavePemission;
}

- (NSString *)serialNumberByCode:(NSString *)code {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAMPLE_CODE WHERE SAMPLE_QR_CODE = '%@'", code];
    FMResultSet *result = [db executeQuery:sql];
    
    NSString *seriesNumber;
    while ([result next]) {
        seriesNumber = [result stringForColumn:@"SERIES_NUMBER"];
    }
    return seriesNumber;
}

// 二维码存在
- (void)popCodeExistView:(NSString *)number {
    //二维码成功后 置为5
    self.number=5;
    // 底层view
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    self.mainView = mainView;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView];
    //    mainView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    mainView.backgroundColor = [UIColor whiteColor];
    
    // 取样成功view
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 64)];
    [mainView addSubview:topView];
    topView.backgroundColor = [TTTheme defaultManger].selectColor;
    
    //设置返回按钮
    UIButton *backBtn=[[UIButton alloc]init];
    backBtn.userInteractionEnabled=NO;

    [backBtn setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [topView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(5);
        make.centerY.mas_equalTo(topView.mas_centerY).mas_offset(10);
        make.width.offset(30);
        make.height.offset(30);
    }];
//    [backBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    // 取样成功label
    UILabel *topLabel = [[UILabel alloc] init];
    [topView addSubview:topLabel];
    topLabel.text = @"取样成功";
    [topLabel sizeToFit];
    topLabel.textColor = [UIColor whiteColor];
    topLabel.font = [UIFont systemFontOfSize:17.0];
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topView.mas_centerX);
        make.centerY.mas_equalTo(topView.mas_centerY).mas_offset(10);
        make.width.offset(100);
        make.height.offset(30);
    }];

    // view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, DEF_SCREEN_HEIGHT / 4, DEF_SCREEN_WIDTH - 20, 250 * BIZ)];
    [mainView addSubview:view];
    
    view.backgroundColor = UIColorFromRGB(0xe7e7e7);
    //将图层的边框设置为圆脚
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((view.frame.size.width - 80) / 2, 20*BIZ, 80*BIZ, 80*BIZ)];
    [view addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"cunzai"];
    
    // label
    UILabel *label = [[UILabel alloc] init];
    [view addSubview:label];
    [label setTextColor:[UIColor blackColor]];
    label.font = [UIFont systemFontOfSize:20.0];
    label.text = @"二维码存在!";
    [label sizeToFit];
    
    CGPoint point;
    point.x = view.center.x - 10*BIZ;
    point.y = view.center.y - view.frame.origin.y;
    label.center = point;
    
    // 请扫描防伪码
    UILabel *securityLabel = [[UILabel alloc] init];
    [view addSubview:securityLabel];
    [securityLabel setTextColor:[UIColor blackColor]];
    securityLabel.font = [UIFont systemFontOfSize:20.0];
    securityLabel.text = @"请刮开涂层扫描防伪验证码";
    [securityLabel sizeToFit];
    
    CGPoint securityPoint;
    securityPoint.x = view.center.x - 10*BIZ;
    securityPoint.y = CGRectGetMaxY(label.frame) + 20*BIZ;
    securityLabel.center = securityPoint;
    
    // 防伪码扫描btn
    UIButton *sweepBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [view addSubview:sweepBtn];
    sweepBtn.tag = 2;
    [sweepBtn setBackgroundImage:[UIImage imageNamed:@"saoma"] forState:UIControlStateNormal];
    
    CGPoint btnPoint;
    btnPoint.x = view.center.x - 10*BIZ;
    btnPoint.y = CGRectGetMaxY(securityLabel.frame) + 30*BIZ;;
    sweepBtn.center = btnPoint;
    [sweepBtn addTarget:self action:@selector(clickAddBtn:) forControlEvents:UIControlEventTouchUpInside];
}

// 防伪码正确 继续扫描二维码
- (void)popSecurityCodeTureView:(NSArray *)fangweiArr {
    // 底层view
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    self.mainView = mainView;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView];
    //    mainView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    mainView.backgroundColor = [UIColor whiteColor];
    
    // 取样成功view
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 64)];
    [mainView addSubview:topView];
    topView.backgroundColor = [TTTheme defaultManger].selectColor;
    
    // 取样成功label
    UILabel *topLabel = [[UILabel alloc] init];
    [topView addSubview:topLabel];
    topLabel.text = @"取样成功";
    [topLabel sizeToFit];
    topLabel.textColor = [UIColor whiteColor];
    topLabel.font = [UIFont systemFontOfSize:17.0];
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topView.mas_centerX);
        make.centerY.mas_equalTo(topView.mas_centerY).mas_offset(10);
        make.width.offset(100);
        make.height.offset(30);
    }];
    
    // view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, DEF_SCREEN_HEIGHT / 4, DEF_SCREEN_WIDTH - 20, 300 * BIZ)];
    [mainView addSubview:view];
    
    view.backgroundColor = UIColorFromRGB(0xe7e7e7);
    //将图层的边框设置为圆脚
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((view.frame.size.width - 80) / 2, 20*BIZ, 80*BIZ, 80*BIZ)];
    [view addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"cunzai"];
    
    // label
    UILabel *label = [[UILabel alloc] init];
    [view addSubview:label];
    [label setTextColor:[UIColor blackColor]];
    label.font = [UIFont systemFontOfSize:20.0];
    label.text = @"防伪码正确!";
    [label sizeToFit];
    
    CGPoint point;
    point.x = view.center.x - 10*BIZ;
    point.y = CGRectGetMaxY(imageView.frame) + 20*BIZ;
    label.center = point;
    
    
    // 几次label
    UILabel *timeLabel = [[UILabel alloc] init];
    [view addSubview:timeLabel];
    [timeLabel setTextColor:[UIColor blackColor]];
    timeLabel.font = [UIFont systemFontOfSize:15.0];
    
    NSInteger x = (fangweiArr.count - self.qrCodeArr.count);
    NSString *timeStr = [NSString stringWithFormat:@"您还需要扫%d次二维码", x];
    
    timeLabel.text = timeStr;
    [timeLabel sizeToFit];
    
    CGPoint timePoint;
    timePoint.x = view.center.x - 10*BIZ;
    timePoint.y = CGRectGetMaxY(label.frame) + 10*BIZ;
    timeLabel.center = timePoint;
    
    // 请扫描二维码
    UILabel *securityLabel = [[UILabel alloc] init];
    [view addSubview:securityLabel];
    [securityLabel setTextColor:[UIColor blackColor]];
    securityLabel.font = [UIFont systemFontOfSize:20.0];
    securityLabel.text = @"请扫描二维码 : ";
    [securityLabel sizeToFit];
    
    CGPoint securityPoint;
    securityPoint.x = view.center.x - 10*BIZ;
    securityPoint.y = CGRectGetMaxY(timeLabel.frame) + 20*BIZ;
    securityLabel.center = securityPoint;
    
    // 第二次以后二维码扫描btn
    UIButton *sweepBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [view addSubview:sweepBtn];
    sweepBtn.tag = 1;
    [sweepBtn setBackgroundImage:[UIImage imageNamed:@"saoma"] forState:UIControlStateNormal];
    CGPoint btnPoint;
    btnPoint.x = view.center.x - 10*BIZ;
    btnPoint.y = CGRectGetMaxY(securityLabel.frame) + 40*BIZ;
    sweepBtn.center = btnPoint;
    [sweepBtn addTarget:self action:@selector(secondSaoMa) forControlEvents:UIControlEventTouchUpInside];
}

// 防伪验证
//- (BOOL)securityExist:(NSString *)securityCode {
//    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
//    [db open];
//    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAMPLE_CODE WHERE SAMPLE_QR_CODE = '%@' AND SAMPLE_SECURITY_CODE = '%@'", self.erCode, securityCode];
//    FMResultSet *result=[db executeQuery:sql];
//    
//    BOOL state = false;
//    while ([result next]) {
//        state = YES;
//    }
//    [db close];
//    return state;
//}

// 修改见证取样流程表
- (void)modifySampleProcess:(NSString *)state {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 防伪码字符串
    NSString *tempString = [self.securityCodeArr componentsJoinedByString:@","];
    // 修改流程
    NSString *sqlStr2 = [NSString stringWithFormat:@"UPDATE SAMPLE_PROCESS SET SAMPLE_CHECK_USER = '%@', SAMPLE_SECURITY_CODE = '%@', SAMPLE_PROCESS_STATE = '%@', LOCAL_MODIFY_STATE = 'MOD', MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'", USERID, tempString, state, DEF_PERSISTENT_GET_OBJECT(@"realname"), [LSUtility getIPAddress], [LSUtility nowTime], self.processDic[@"ID"]];
    if([db executeUpdate:sqlStr2]) {
        NSLog(@"修改见证取样成功");
    } else {
        NSLog(@"修改见证取样失败");
    }
    [db close];
}

#pragma mark - 新增见证取样记录
- (void)addFlowRecordData:(NSString *)state {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    DBHelper *dbhelper = [DBHelper help];
    
    // 查询见证取样流程
    //    NSString *sql = [NSString stringWithFormat:@"SELECT ID FROM SAMPLE_PROCESS WHERE SAMPLE_QR_CODE = '%@'", self.erCode];
    //    FMResultSet *result = [db executeQuery:sql];
    //
    //    NSString *processID;
    //    while ([result next]) {
    //        processID = [result stringForColumn:@"ID"];
    //    }
    
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":[NSUUID UUID].UUIDString,
                 @"PROCESS_ID":DEFISNUL(self.processDic[@"ID"]),
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"RECORD_TIME":[LSUtility nowTime],
                 @"RECORD_USER":DEFISNUL(USERID),
                 @"RECORD_CONTENT":@"",
                 @"SAMPLE_WITNESS_RESULT":@"",
                 @"SAMPLE_WITNESS_SCORE":@"",
                 @"SAMPLE_WITNESS_REVIEW":@"",
                 @"SAMPLE_CHECK_TORF_RESULT":@"",
                 @"SAMPLE_CHECK_TORF_DESC":@"",
                 @"SAMPLE_CHECK_RESULT":@"",
                 @"SAMPLE_CHECK_DESC":@"",
                 @"SAMPLE_CHECK_RESULT_DESC":@"",
                 @"SAMPLE_CHECK_RESULT_SCORE":@"",
                 @"SAMPLE_PROCESS_STATE":DEFISNUL(state),
                 @"RECORD_DESC":@"",
                 @"EXTEND_INFO":@"",
                 @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"MODIFY_TIME":DEFISNUL([LSUtility nowTime]),
                 @"LOCAL_MODIFY_USER_NAME":@"",
                 @"LOCAL_MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SAMPLE_PROCESS_RECORD];
    if(isAdd){
        NSLog(@"见证取样记录新增成功");
    }else{
        NSLog(@"见证取样记录新增成功");
    }
    [db close];
}

// 修改
- (void)popView:(NSString *)imageName withTitle:(NSString *)title withDetail:(NSString *)detail andBth:(NSString *)btnStr andResult:(NSString *)result andType:(BOOL)type {
    // 底层view
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    self.mainView = mainView;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView];
    mainView.backgroundColor = [UIColor lightGrayColor];
    
    // view
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 64)];
    [mainView addSubview:topView];
    topView.backgroundColor = [TTTheme defaultManger].selectColor;
    
    //设置返回按钮
    UIButton *backBtn=[[UIButton alloc]init];
    backBtn.userInteractionEnabled=NO;
    [backBtn setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [topView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(5);
        make.centerY.mas_equalTo(topView.mas_centerY).mas_offset(10);
        make.width.offset(30);
        make.height.offset(30);
    }];
//    [backBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    // 取样成功label
    UILabel *topLabel = [[UILabel alloc] init];
    [topView addSubview:topLabel];
    topLabel.text =result;
    [topLabel sizeToFit];
    topLabel.textColor = [UIColor whiteColor];
    topLabel.font = [UIFont systemFontOfSize:17.0];
    topLabel.center = topView.center;
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topView.mas_centerX);
        make.centerY.mas_equalTo(topView.mas_centerY).mas_offset(10);
        make.width.offset(100);
        make.height.offset(30);
    }];

    // view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, DEF_SCREEN_HEIGHT / 4, DEF_SCREEN_WIDTH - 20, 250 * BIZ)];
    [mainView addSubview:view];
    
    view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    //将图层的边框设置为圆脚
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((view.frame.size.width - 80) / 2, 20*BIZ, 80*BIZ, 80*BIZ)];
    [view addSubview:imageView];
    imageView.image = [UIImage imageNamed:imageName];
    
    // label
    UILabel *label = [[UILabel alloc] init];
    [view addSubview:label];
    [label setTextColor:[UIColor blackColor]];
    label.font = [UIFont systemFontOfSize:20.0];
    label.text = title;
    [label sizeToFit];
    
    CGPoint point;
    point.x = view.center.x - 10*BIZ;
    point.y = view.center.y - view.frame.origin.y;
    label.center = point;
    
    // 二维码label
    UILabel *erweimaLabel = [[UILabel alloc] init];
    [view addSubview:erweimaLabel];
    [erweimaLabel setTextColor:[UIColor blackColor]];
    erweimaLabel.font = [UIFont systemFontOfSize:20.0];
    
    if ([title isEqualToString:@"防伪验证不通过!"] ||[title isEqualToString:@"二维不存在"]||[title isEqualToString:@"此二维码被扫过"]) {
        //找到数字位置
        NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        int remainSecond =[[detail stringByTrimmingCharactersInSet:nonDigits] intValue];
        NSRange range=[detail rangeOfString:[NSString stringWithFormat:@"%i",remainSecond]];
        //标红
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:detail];
        [AttributedStr addAttribute:NSForegroundColorAttributeName
                              value:[UIColor redColor]
                              range:range];
        erweimaLabel.attributedText = AttributedStr;
        erweimaLabel.font = [UIFont systemFontOfSize:15.0];
        
    } else {
        erweimaLabel.text = detail;
    }
    [erweimaLabel sizeToFit];
    
    CGPoint erweimaPoint;
    erweimaPoint.x = view.center.x - 10*BIZ;
    erweimaPoint.y = view.center.y - view.frame.origin.y + 30*BIZ;
    erweimaLabel.center = erweimaPoint;
    
    if (type) {
        // 重新扫描
        UIButton *toScan = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        [view addSubview:toScan];
        toScan.tag = 2;
        // 将图层的边框设置为圆脚
        toScan.layer.cornerRadius = 8;
        toScan.layer.masksToBounds = YES;
        toScan.backgroundColor = UIColorFromRGB(0x549587);
        
        [toScan setTitle:@"重新扫描" forState:UIControlStateNormal];
        [toScan.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
        [toScan.titleLabel setTextColor:[UIColor whiteColor]];
        //扫二维码
        if([title isEqualToString:@"二维不存在"]||[title isEqualToString:@"此二维码被扫过"]){
            [toScan addTarget:self action:@selector(secondSaoMa) forControlEvents:UIControlEventTouchUpInside];
        }else{
                 [toScan addTarget:self action:@selector(clickAddBtn:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        CGPoint btnPoint;
        btnPoint.x = view.frame.size.width/3;
        btnPoint.y = view.center.y - view.frame.origin.y + 80*BIZ;
        toScan.center = btnPoint;
        
        // 返回列表
        UIButton *returnBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        [view addSubview:returnBtn];
        // 将图层的边框设置为圆脚
        returnBtn.layer.cornerRadius = 8;
        returnBtn.layer.masksToBounds = YES;
        
        returnBtn.backgroundColor = [UIColor colorWithRed:0.40 green:0.40 blue:0.40 alpha:1.00];
        
        [returnBtn setTitle:@"返回列表" forState:UIControlStateNormal];
        [returnBtn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
        [returnBtn.titleLabel setTextColor:[UIColor whiteColor]];
        [returnBtn addTarget:self action:@selector(clicksReturnBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        CGPoint returnPoint;
        returnPoint.x = view.frame.size.width/3 * 2;
        returnPoint.y = view.center.y - view.frame.origin.y + 80*BIZ;
        returnBtn.center = returnPoint;
        
    } else {
        // 确定按钮
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        [view addSubview:btn];
        // 将图层的边框设置为圆脚
        btn.layer.cornerRadius = 8;
        btn.layer.masksToBounds = YES;
        
        btn.backgroundColor = UIColorFromRGB(0x549587);
        [btn setTitle:btnStr forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
        [btn.titleLabel setTextColor:[UIColor whiteColor]];
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        CGPoint btnPoint;
        btnPoint.x = view.center.x - 10*BIZ;
        btnPoint.y = view.center.y - view.frame.origin.y + 80*BIZ;
        btn.center = btnPoint;
    }
}


// 返回列表
- (void)clicksReturnBtn:(UIButton *)btn {
    
    
    [self.mainView removeFromSuperview];
    NSString *str = @"您确定返回列表吗?\n如果返回, 此见证取样单防伪不通过";
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"返回列表" message:str preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.mainView removeFromSuperview];
        // 修改见证取样流程
        [self modifySampleProcess:@"3"];
        // 新增见证取样流程记录
        [self addFlowRecordData:@"3"];
        // 初始化列表
        [self reloadGJList];
        if(header){
            [header beginRefreshing];
        }
        [self.mainView removeFromSuperview];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *str = [NSString stringWithFormat:@"请您重新输入，还有%d次机会", self.number];
        [self popView:@"fangweicuowu" withTitle:@"防伪验证不通过!" withDetail:str andBth:nil andResult:@"取样成功" andType:YES];
    }];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

//点击弹出视图
- (void)clickAlert:(UIButton *)sender{
    [self.alertView removeFromSuperview];
    
    NSInteger tag=sender.tag;
    if(tag==100){
        [self.mainView removeFromSuperview];
        // 修改见证取样流程
        [self modifySampleProcess:@"3"];
        // 新增见证取样流程记录
        [self addFlowRecordData:@"3"];
        // 初始化列表
        [self reloadGJList];
        
    }else{
        NSString *str = [NSString stringWithFormat:@"请您重新输入，还有%d次机会", self.number];
        [self popView:@"fangweicuowu" withTitle:@"防伪验证不通过!" withDetail:str andBth:nil andResult:@"取样成功" andType:YES];
    }
    
}

// 防伪验证通过(点击查看)
- (void)clickBtn:(UIButton *)btn {
    self.mainView.alpha = 0.0;
    [self.mainView removeFromSuperview];
    
    // 验证通过
    if ([btn.titleLabel.text isEqualToString:@"查看"]) {
        
        WitnessSamplesDetailVC *wsDetailVC = [[WitnessSamplesDetailVC alloc] init];
        
        SampleProcessModel *spModel = [self inquirySampleProcess];
        
        wsDetailVC.spModel = spModel;
        NSLog(@"id：%@",spModel.ID);
        wsDetailVC.isEdit = NO;
        
        [self.navigationController pushViewController:wsDetailVC animated:YES];
        
        if(header){
            [header beginRefreshing];
        }
        // 验证不通过
    } else if ([btn.titleLabel.text isEqualToString:@"重新输入"]) {

    }
}

// 查询验证通过的流程模型
- (SampleProcessModel *)inquirySampleProcess {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    /*
     *  根据二维码 防伪码 查询流程  模糊查询
     */
    
//    NSString *sql = [NSString stringWithFormat:@"select  * from SAMPLE_PROCESS where  SAMPLE_QR_CODE  like '%%%@%%'", self.erCode];
    NSString *sql = [NSString stringWithFormat:@"select  * from SAMPLE_PROCESS where  id  = '%@'",  self.responseObjectDic[@"id"]];
    
    FMResultSet *result=[db executeQuery:sql];
    
    SampleProcessModel *spModel = [[SampleProcessModel alloc] init];
    while ([result next]) {
        spModel.ID = [result stringForColumn:@"ID"];
        spModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        spModel.SAMPLE_NUMBER = [result stringForColumn:@"SAMPLE_NUMBER"];
        spModel.SAMPLE_GET_TIME = [result stringForColumn:@"SAMPLE_GET_TIME"];
        spModel.SAMPLE_GET_ADDRESS = [result stringForColumn:@"SAMPLE_GET_ADDRESS"];
        spModel.SAMPLE_GET_ADDRESS_INFO = [result stringForColumn:@"SAMPLE_GET_ADDRESS_INFO"];
        spModel.SAMPLE_WINESS_USER = [result stringForColumn:@"SAMPLE_WINESS_USER"];
        spModel.SAMPLE_QR_CODE = [result stringForColumn:@"SAMPLE_QR_CODE"];
        spModel.SAMPLE_PROCESS_STATE = [result stringForColumn:@"SAMPLE_PROCESS_STATE"];
        spModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        spModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        spModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        spModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        spModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        spModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        spModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
    }
    [db close];
    return spModel;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    SampleProcessModel *spModel = array[indexPath.row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    cell.gengduo.hidden=YES;
    // 列表标题
    NSString *titleStr = [NSString stringWithFormat:@"%@日_%@_见证取样工作", spModel.day, spModel.SAMPLE_NUMBER];
    cell.title.text = titleStr;
    cell.title.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:16.*BIZ];
    cell.state.textColor = UIColorFromRGB(0x549587);
    
    if ([spModel.SAMPLE_PROCESS_STATE isEqualToString:@"1"]) {
        cell.state.text = @"待检验";
        
    } else if ([spModel.SAMPLE_PROCESS_STATE isEqualToString:@"2"]) {
        cell.state.text = @"防伪通过";
        
    } else if ([spModel.SAMPLE_PROCESS_STATE isEqualToString:@"3"]) {
        cell.state.text = @"防伪不通过";
        
    }
    return cell;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame =CGRectMake(0, 8, DEF_SCREEN_WIDTH, CELL_HEIGHT-10);
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    //设置分组标题
    [eButton setTitle:[[_dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:14.];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIImage *image = eButton.imageView.image;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, image.size.width)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, eButton.titleLabel.bounds.size.width+20, 0, -eButton.titleLabel.bounds.size.width)];
    
    //添加btn
    [hView addSubview: eButton];
    
    return hView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70 * BIZ;
}


#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WitnessSamplesDetailVC *jzqyVC=[[WitnessSamplesDetailVC alloc]init];
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    SampleProcessModel *spModel = array[indexPath.row];
    NSLog(@"id：%@",spModel.ID);
    jzqyVC.spModel = spModel;
    jzqyVC.isEdit = NO;
    
    [self.navigationController pushViewController:jzqyVC animated:YES];
}

#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

//返回指定节是否是展开的

-(int)isExpanded:(long)section{
    NSDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end





